<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('需求管理')" />
	<th:block th:include="include :: select2-css" />
</head>
<body class="gray-bg">
     <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="formId">
                    <div class="select-list">
                        <ul>
							<li>
							    <label>状态：</label>
								<select id="statusId" name="statusId" class="form-control">
									<option value="">所有</option>
									<option value="0" selected>打开</option>
								    <option th:each="issueStatuse : ${issueStatuseList}" th:text="${issueStatuse['name']}" th:value="${issueStatuse['id']}"></option>
								</select>
							</li>
							<li>
							    <label>项目：</label>
								<select id="projectId" name="projectId" class="form-control">
									<option value="">所有</option>
								    <option th:each="project : ${projectList}" 
								           th:text="${project['name'] + ' (' + project['customerName'] + ')'}" 
								           th:value="${project['id']}"
								           th:selected="${projectId != null and projectId == project['id']}"></option>
								</select>
							</li>
                            <li>
                               <label>跟踪：</label>
								<select id="trackerId" name="trackerId" class="form-control">
							   		<option value="">所有</option>
								    <option th:each="tracker : ${trackerList}" th:text="${tracker['name']}" th:value="${tracker['id']}"></option>
								</select>
                            </li>
                            <li>
                                <label>主题：</label>
                                <input type="text" name="subject"/>
                            </li>
							<li>
							    <label>作者：</label>
								<select id="authorId" name="authorId" class="form-control" >		
									<option value="">所有</option>
									<option th:each="user : ${userList}" th:text="${user['userName']}" th:value="${user['userId']}"></option>
								</select>
							</li>
                            <li>
                                <label>指派给：</label>
								<select id="assignedToId" name="assignedToId" class="form-control" >			
									<option value="">&emsp;</option>
									<option th:each="user : ${userList}" th:text="${user['userName']}" th:value="${user['userId']}" th:selected="${user['userId'] == curUserId}"></option>
								</select>
                            </li>
                            <li>
                                <label>优先级：</label>
								<select id="priorityId" name="priorityId" class="form-control" >	
									<option value="">所有</option>
									<option th:each="issuePrioritie : ${issuePrioritieList}" th:text="${issuePrioritie['name']}" th:value="${issuePrioritie['id']}"></option>
								</select>
                            </li>
                            <li>
                                <label>% 进度：</label>
								<select name="doneRatio" id="doneRatio" class="form-control">
									<option value="">所有</option>
									<option value="0">0 %</option>
									<option value="10">10 %</option>
									<option value="20">20 %</option>
									<option value="30">30 %</option>
									<option value="40">40 %</option>
									<option value="50">50 %</option>
									<option value="60">60 %</option>
									<option value="70">70 %</option>
									<option value="80">80 %</option>
									<option value="90">90 %</option>
									<option value="100">100 %</option>
								</select>
                            </li>
                            <li style="display: flex; align-items: center;">
                                <label style="white-space: nowrap; margin: 0; min-width: 60px;">开始时间：</label>
                                <input type="date" name="sDate" id="startDate" class="form-control" style="flex: 1; min-width: 150px;" />
                            </li>
                            <li style="display: flex; align-items: center;">
                                <label style="white-space: nowrap; margin: 0; min-width: 60px;">结束时间：</label>
                                <input type="date" name="eDate" id="endDate" class="form-control" style="flex: 1; min-width: 150px;" />
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-success" onclick="$.operate.addTab()" shiro:hasPermission="project:issue:add">
                    <i class="fa fa-plus"></i> 新增
                </a>
                <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="project:issue:edit">
                    <i class="fa fa-edit"></i> 编辑
                </a>
                <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="project:issue:remove">
                    <i class="fa fa-remove"></i> 删除
                </a>
                <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="project:issue:export">
                    <i class="fa fa-download"></i> 导出
                </a>
                <a class="btn btn-info" onclick="syncData()" shiro:hasPermission="project:issue:sync">
                    <i class="fa fa-refresh"></i> 同步数据
                </a>
				<a class="btn btn-danger" onclick="closeItem()" th:if="${goBack}">
				    <i class="fa fa-reply-all"></i> 关闭
				</a>
            </div>
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
	<th:block th:include="include :: select2-js" />
	<script th:src="@{/js/pm/issue.js}"></script>
    <script th:inline="javascript">
		var curUser = [[${curUser}]];
		var detailFlag = [[${@permission.hasPermi('project:issue:detail')}]];
        var editFlag = [[${@permission.hasPermi('project:issue:edit')}]];
        var removeFlag = [[${@permission.hasPermi('project:issue:remove')}]];
        var prefix = ctx + "project/issue";

        $(function() {
            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/new",
				detailUrl: prefix + "/{id}",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
				sortName: "createTime",
				sortOrder: "desc",
				modalName: "需求",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'id',
                    title: '#',
                    switchable: false,
                    formatter: function(value, row, index) {
                        return '<a class="' + detailFlag + '" href="javascript:void(0)" onclick="$.operate.detailTab(\'' + row.id + '\')">' + value + '</a>';
                    }
                },
				{
				    field: 'subject',
				    title: '主题',
                    formatter: function(value, row, index) {
                        if (!value) return '';
                        
                        // 检查是否超时未处理
                        var isOverdue = false;
                        if (row.dueDate) {
                            var dueDate = new Date(row.dueDate);
                            var today = new Date();
                            today.setHours(0, 0, 0, 0);
                            
                            var isResolved = row.statusId == 4 || row.statusId == 6; // 4=已解决, 6=已关闭
                            isOverdue = dueDate < today && !isResolved;
                        }
                        
                        var subjectStyle = isOverdue ? 'style="color: #ff4d4f; font-weight: bold;"' : '';
                        return '<a class="' + detailFlag + '" href="javascript:void(0)" onclick="$.operate.detailTab(\'' + row.id + '\')" ' + subjectStyle + '>' + value + '</a>';
                    }
				},
                {
                    field: 'projectName',
                    title: '项目'
                },
                {
                    field: 'trackerName',
                    title: '跟踪'
                },
                {
                    field: 'statusName',
                    title: '状态',
					formatter: function(value, row, index) {
						var listClass = $.common.equals("default", row.issueStatus.htmlColor) || $.common.isEmpty(row.issueStatus.htmlColor) ? "" : "badge badge-" + row.issueStatus.htmlColor;
						var cssClass = $.common.isNotEmpty(row.cssClass) ? row.cssClass : listClass;
						return $.common.sprintf("<span class='%s'>%s</span>", cssClass, value);
					}
                },
                {
                    field: 'description',
                    title: '描述',
                    visible: false
                },
                {
                    field: 'assignedToName',
                    title: '指派给'
                },
                {
                    field: 'priorityName',
                    title: '优先级',
					formatter: function(value, row, index) {
						var listClass = $.common.equals("default", row.priority.listClass) || $.common.isEmpty(row.priority.listClass) ? "" : "badge badge-" + row.priority.listClass;
						var cssClass = $.common.isNotEmpty(row.cssClass) ? row.cssClass : listClass;
						return $.common.sprintf("<span class='%s'>%s</span>", cssClass, value);
					}
                },
                {
                    field: 'authorName',
                    title: '作者'
                },
                {
                    field: 'dueDate',
                    title: '截止日期',
                    formatter: function(value, row, index) {
                        if (!value) return '';
                        
                        var dueDate = new Date(value);
                        var today = new Date();
                        today.setHours(0, 0, 0, 0);
                        
                        // 检查是否超时未处理（截止日期已过且状态不是已解决或已关闭）
                        var isOverdue = dueDate < today;
                        var isResolved = row.statusId == 4 || row.statusId == 6; // 4=已解决, 6=已关闭
                        
                        if (isOverdue && !isResolved) {
                            // 计算延期天数
                            var timeDiff = today.getTime() - dueDate.getTime();
                            var daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
                            
                            var overdueText = '';
                            if (daysDiff === 1) {
                                overdueText = ' (一天延期)';
                            } else if (daysDiff > 1) {
                                overdueText = ' (' + daysDiff + '天延期)';
                            }
                            
                            return '<span style="color: #ff4d4f; font-weight: bold;">' + value + overdueText + '</span>';
                        } else {
                            return value;
                        }
                    }
                },
				{
				    field: 'createTime',
				    title: '发布时间'
				},
				{
				    field: 'updateTime',
				    title: '更新于'
				},
                {
                    title: '操作',
                    align: 'center',
					switchable: false,
                    formatter: function(value, row, index) {
                        var actions = [];
						if(row.statusId == 1){
	                        actions.push('<a class="btn btn-warning btn-xs ' + '" href="javascript:void(0)" onclick="claimIssue(\'' + row.id + '\')"><i class="fa fa-hand-paper-o"></i>领取</a> ');
						}
						if(row.statusId == 2 && (curUser.userId == row.assignedToId || curUser.userId == row.authorId || curUser.admin)){
	                        actions.push('<a class="btn btn-info btn-xs ' + '" href="javascript:void(0)" onclick="submitIssue(\'' + row.id + '\')"><i class="fa fa-send"></i>提交</a> ');
						}
						if(row.statusId == 3 && (curUser.userId == row.authorId || curUser.userId == row.authorId || curUser.admin)){
	                        actions.push('<a class="btn btn-primary btn-xs ' + '" href="javascript:void(0)" onclick="reviewIssue(\'' + row.id + '\')"><i class="fa fa-send"></i>审核</a> ');
						}
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
						if(curUser.userId == row.authorId || curUser.admin){
	                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
						}
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
        });

        // 同步数据函数
        function syncData() {
            layer.confirm('确定要同步第二数据源的数据吗？', {
                icon: 3,
                title: '同步确认'
            }, function(index) {
                $.ajax({
                    url: ctx + "system/sync/syncXuqiuToIssue",
                    type: "GET",
                    beforeSend: function() {
                        layer.load(2);
                    },
                    success: function(result) {
                        layer.closeAll();
                        if (result.code == 0) {
                            layer.msg("同步成功！", {icon: 1});
                            // 刷新表格数据
                            $.table.refresh();
                        } else {
                            layer.msg("同步失败：" + result.msg, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.closeAll();
                        layer.msg("同步请求失败", {icon: 2});
                    }
                });
                layer.close(index);
            });
        }
    </script>
</body>
</html>